package com.szcinda.call.phone;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szcinda.call.CallController;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class PhoneCall {

    private static final String ACCOUNT_SID = "ced073d87ce003bffaa26ce8cd1a585f";
    private static final String AUTH_TOKEN = "5344ca7aa721df79bfc72b35dc33357c";
    private static final String DATE_FORMAT = "yyyyMMddHHmmss";
    private static final String BASE_URL = "https://api.139130.com:9999/api/v1.0.0";
    private static final String NOTIFICATION_URL = "/voice/notify";
    private static final String SIG_PARAM_STR = "?sig=";
    private static final String JSON_CONTENT_TYPE = "application/json;charset=utf-8";

    /*获取yyyyMMddHHmmss格式时间戳*/
    private static String getTimeStamp() {
        return new SimpleDateFormat(DATE_FORMAT).format(new Date());
    }

    /*获取sig字符串*/
    private static String getSig(String timestamp) {
        return DigestUtils.sha1Hex(ACCOUNT_SID + AUTH_TOKEN + timestamp).toLowerCase();
    }

    /*获取请求完整URL*/
    private static String getUrl(String sig) {
        return BASE_URL + NOTIFICATION_URL + SIG_PARAM_STR + sig;
    }

    /*获取Authorization*/
    private static String getAuthorization(String timestamp) {
        return Base64.encodeBase64String((ACCOUNT_SID + ":" + timestamp).getBytes());
    }

    /*获取完整HttpURLConnection对象*/
    private static HttpURLConnection getConnection(String url, String authorization, int length) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", JSON_CONTENT_TYPE);
        conn.setRequestProperty("Accept", JSON_CONTENT_TYPE);
        conn.setRequestProperty("Authorization", authorization);
        conn.setRequestProperty("Content-Length", length + "");
        return conn;
    }

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /*获取请求body*/
    private static String getJsonRequestBody(String called, String data) throws Exception {
        String appId = "c3c1e44d02d17f1d2edd80661f1afcc4";
        String templateId = "27095";
        /*String calledDisplay = "";*/

        Map<String, Object> request = new HashMap<>();

        Map<String, Object> info = new HashMap<>();
        info.put("appID", appId);

        Map<String, Object> subject = new HashMap<>();
        subject.put("called", called);
        /*subject.put("calledDisplay", calledDisplay);*/
        subject.put("templateID", templateId);

        /*List<String> params = new ArrayList<>();
        params.add("8888");
        params.add("456");
        params.add("abc");

        subject.put("params", params);*/
        subject.put("playTimes", 3);

        request.put("info", info);
        request.put("subject", subject);
        request.put("data", data);
        request.put("timestamp", String.valueOf(System.currentTimeMillis()));

        return objectMapper.writeValueAsString(request);
    }

    /*打印请求响应结果*/
    private static void printResponse(HttpURLConnection conn) throws IOException {
        StringBuilder response = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            response.append(tmp);
        }
        System.out.println("response:" + response.toString());
    }

    private static String getResponse(HttpURLConnection conn) throws IOException{
        StringBuilder response = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            response.append(tmp);
        }
        System.out.println("response:" + response.toString());
        return response.toString();
    }

    public static CallbackData call(String phone, String data){
        try {
            String timestamp = getTimeStamp();
            String sig = getSig(timestamp);
            String url = getUrl(sig);
            String authorization = getAuthorization(timestamp);
            String requestContent = getJsonRequestBody(phone, data);
            HttpURLConnection conn = getConnection(url, authorization, requestContent.length());
            DataOutputStream output = new DataOutputStream(conn.getOutputStream());
            output.write(requestContent.getBytes(StandardCharsets.UTF_8));
            output.close();
//            printResponse(conn);
            String result = getResponse(conn);
            return objectMapper.readValue(result, CallbackData.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception{
        String timestamp = getTimeStamp();
        String sig = getSig(timestamp);
        String url = getUrl(sig);
        String authorization = getAuthorization(timestamp);
        String requestContent = getJsonRequestBody("13112274760", "test");
        HttpURLConnection conn = getConnection(url, authorization, requestContent.length());
        DataOutputStream output = new DataOutputStream(conn.getOutputStream());
        output.write(requestContent.getBytes(StandardCharsets.UTF_8));
        output.close();
        printResponse(conn);
    }
}
